package interceptor

import (
	"context"
	"emailcenter/utils/logx"
	"fmt"
	"google.golang.org/grpc"
	"google.golang.org/grpc/peer"
	"google.golang.org/grpc/status"
	"io"
	"os"
	"strings"
	"time"
)

// TODO GOLANG-1.18 范型

func LogInterceptor(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {
	// 拦截器-前
	startTime := time.Now()

	midResp, err := handler(ctx, req)

	// 拦截器-后
	// 业务信息
	endTime := time.Now()
	latencyTime := endTime.Sub(startTime)
	p, _ := peer.FromContext(ctx)
	statusCode := status.Code(err)

	// 监控日期变化
	if logx.LogFileCreateTime.Day() != startTime.Day() {
		logx.LogFileLock.Lock()
		_ = logx.LogFile.Close()
		logx.LogFile, _ = logx.NewLogFile()
		logx.LogFileInfo, _ = logx.LogFile.Stat()
		logx.LogFileCreateTime = logx.LogFileInfo.ModTime()
		logx.LogrusObj.SetOutput(io.MultiWriter(logx.LogFile, os.Stdout))
		logx.LogFileLock.Unlock()
	}

	// 终端输出 (colorful)
	msg := fmt.Sprintf("| %2d | %13v | %15s | %s ", statusCode, latencyTime, p.Addr, strings.Split(info.FullMethod, "/")[2])
	//fmt.Println("[RPC]", time.Now().Format("06/01/02-15:04:05"), msg)

	// writer 输出
	logx.LogrusObj.Info("[RPC] " + msg)

	return midResp, err
}
